﻿using System;
using System.Text;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;

namespace Testrabbitmq
{
    class Program
    {
        static void Main(string[] args)
        {
            //ProduceMessage();
            ConsumeMessage();

        }

        public static void ProduceMessage()
        {
            var factory = new ConnectionFactory
            {
                HostName = "192.168.11.112",
                Port = 32690,
                UserName = "guest",
                Password = "123ZXCvbn!@#"
            };

            using var connection = factory.CreateConnection();
            using var channel = connection.CreateModel();

            channel.QueueDeclare("hello", false, false, false, null);
            string message = "Hello World";
            var body = Encoding.UTF8.GetBytes(message);
            channel.BasicPublish("", "hello", null, body);
            Console.WriteLine("已发送： {0}", message);
            Console.ReadLine();
        }

        public static void ConsumeMessage()
        {

            var factory = new ConnectionFactory
            {
                HostName = "192.168.11.112",
                Port = 32690,
                UserName = "guest",
                Password = "123ZXCvbn!@#"
            };


            using var connection = factory.CreateConnection();
            using var channel = connection.CreateModel();

            channel.QueueDeclare("hello", false, false, false, null);

            var consumer = new EventingBasicConsumer(channel);
            channel.BasicConsume("hello", false, consumer);

            consumer.Received += (model, ea) =>
            {
                var body = ea.Body;
                var message = Encoding.UTF8.GetString(body.ToArray());
                Console.WriteLine("已接收： {0}", message);
            };
            Console.ReadLine();
        }
    }
}
